<template>
  <div>
    <!-- 导入 -->
    <Card style="margin:10px 0;">
      <h3 class="title-color">第一步:导入问卷</h3>
      <Row style="margin-top:20px">
        <!--
          本地  action="api/examQuestion/uploadQuestion"
          线上  action="/examQuestion/uploadQuestion"
        -->
        <div style="margin-bottom:10px;">
          <Button icon="ios-cloud-download-outline" type="success" @click="downloadTemplate">下载问卷模板</Button>
        </div>
        <Tooltip content="温馨提示:导入题干前，请先下载题干模板，依照模板格式进行导入" placement="bottom-start" max-width="220">
          <Upload
            ref="upload"
            :before-upload="handleUpload"
            :on-success="handleSuccess"
            :format="['xls','xlsx']"
            :on-format-error="handleFormatError"
            :data="datas"
            :action="importUrl"
          >
            <Button type="success" icon="ios-cloud-upload-outline">导入问卷</Button>
          </Upload>
        </Tooltip>

        <div v-if="file !== null">
          文件名: {{ file.name }}
          <Button type="primary" @click="upload">点击上传</Button>
        </div>

        <!-- 上传错误提示 -->
        <div>
          <!-- <Alert banner closable type="error" v-for="item in errorMessage" :key="item">{{item}}</Alert> -->
        </div>
      </Row>
    </Card>

    <!-- 点击"问卷预览"按钮预览问卷 -->
    <Card>
      <h3 class="title-color">第二步:点击"问卷预览"按钮预览问卷</h3>
      <div>
        <Tooltip content="点击按钮查看题干，可以进行题干排序操作" placement="top-start" max-width="270">
          <Button type="primary" @click="showOrhide">显示 / 隐藏题干</Button>
        </Tooltip>
        <Button type="warning" @click="previewExam" style="margin-left:10px;">问卷预览</Button>
      </div>
      <!-- 题干排序表格 -->
      <Row v-if="isHideStem" style="margin-top:10px;">
        <Table :columns="stemHead" :data="stemData" border :loading="examTableLoading">
          <template slot-scope="{ row, index }" slot="stem">
            <Input type="text" v-model="stem" v-if="false" />
            <span v-else>{{ row.stem }}</span>
          </template>

          <template slot-scope="{ row, index }" slot="sort">
            <!-- <Input type="text" v-model="sort" v-if="editIndex === index" /> -->
            <InputNumber :min="1" v-model="sort" v-if="editIndex === index"></InputNumber>
            <span v-else>{{ row.sort }}</span>
          </template>

          <template slot-scope="{ row, index }" slot="action">
            <div v-if="editIndex === index">
              <Button type="success" @click="handleSave(index)">保存</Button>
              <Button type="error" @click="editIndex = -1">取消</Button>
            </div>
            <div v-else>
              <Button type="primary" @click="handleEdit(row, index)">编辑</Button>
              <!-- <Button type="error" @click="stemRemove(index)">删除</Button> -->
            </div>
          </template>
        </Table>
      </Row>
    </Card>

    <!-- 问卷预览 -->
    <Card class="questionnaire" style="margin:10px 0;">
      <h2 align="center">{{examsTitle}}</h2>
      <div align="center">
        <div class="questionnaire-container">
          <Row v-for="(item, index) in previewExams" :key="index" class="question-title">
            <h3>{{index + 1}}.{{item.stem}}</h3>
            <div align="center">
              <RadioGroup>
                <Radio
                  class="radio-items"
                  v-for="(items , indexs) in item.selectList"
                  :key="indexs"
                  :label="items.selectItem"
                ></Radio>
              </RadioGroup>
            </div>
            <Divider />
          </Row>
        </div>
      </div>
    </Card>
  </div>
</template>
<script>
import { URL } from "@/libs/util";
import { generateAjax } from "@/api/measurement";
// 单位请求
import { userAjax } from "@/api/systemMange";
const HOST = URL;
// 问卷修改排序
const UPDEXAM_URL = "/examQuestion/updateSort";
// 问卷查询
const EXAMQUESTION_URL = "/examQuestion/query";
// 问卷预览
const PREVIEW_URL = "/examQuestion/getExamView";
export default {
  data() {
    return {
      searchData: { id: "" }, // 二级页面id
      modalLoading: false,
      tabelLoading: false,
      examTableLoading: false,
      // 题干排序表头
      stemHead: [
        {
          title: "题干/选项",
          slot: "stem"
        },
        {
          title: "排序",
          slot: "sort"
        },
        {
          title: "操作",
          slot: "action",
          width: 170
        }
      ],
      // 生成试卷数据
      datas: {
        // departs: [], // 所选code和简称
        // departNum: 0, // 部门数量
        // options: "", // 所选选项
        // optionId: "", // 所选选项Id
        examId: 0
      },
      stemData: [],
      editIndex: -1, // 当前聚焦的输入框的行数
      stem: "", // 题干
      sort: 1, // 排序
      answer: "",
      // 预览试卷
      previewExams: [],
      examsTitle: "",
      isDisbledBorn: true, // 禁止按钮
      isHideStem: false, // 是否隐藏题干
      errorMessage: [], // 上传错误提示
      file: null,
      importUrl: URL + "/examQuestion/uploadQuestion" // 导入问卷类型二路径
    };
  },
  methods: {
    // 阻止自动上传文件
    handleUpload(file) {
      this.file = file;
      return false;
    },
    // 上传文件
    handleSuccess(res, file) {
      console.log(res);
      if (res.code === "200") {
        this.$Notice.success({
          title: res.message
        });
        this._examQueryAjAX(this.datas, EXAMQUESTION_URL);
      } else if (res.code === "500") {
        // let errorArr = res.results.error;
        // this.errorMessage = errorArr;
        // this.$Notice.error({
        //   title: res.message
        // });
      }
    },
    // 点击上传文件
    upload() {
      this.$refs.upload.post(this.file);
      setTimeout(() => {
        this.file = null;
      }, 1500);
    },
    // 验证上传格式
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式错误",
        desc: "文件" + file.name + " 格式错误, 请选择xls或者xlsx"
      });
    },
    // 题干排序
    handleEdit(row, index) {
      this.stem = row.stem;
      this.sort = row.sort;
      this.editIndex = index;
    },
    stemRemove(index) {
      this.stemData.splice(index, 1);
    },
    // 修改问卷排序保存
    handleSave(index) {
      this.stemData[index].stem = this.stem;
      this.stemData[index].sort = this.sort;
      this.editIndex = -1;
      console.log(this.stemData[index]);
      this._generateExamAjAX(this.stemData[index], UPDEXAM_URL).then(result => {
        if (result.code === "200") {
          // 重新查询排序表格
          this._examQueryAjAX(this.datas, EXAMQUESTION_URL);
          // 重新查询问卷排序
          this._previewExamAjax(this.datas, PREVIEW_URL);
          this.$Message.success("修改成功");
        } else {
          this.$Message.error("修改失败");
        }
      });
    },
    // 插入/修改
    _generateExamAjAX(formData, url) {
      const keyOne = "entity";
      return new Promise((resolve, reject) => {
        generateAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 查询试卷
    _examQueryAjAX(formData, url) {
      const keyOne = "filter";
      this.examTableLoading = true;
      generateAjax({ formData, url, keyOne })
        .then(result => {
          if (result.data.code === "200") {
            this.examTableLoading = false;
            this.stemData = result.data.results.list;
            this.$Message.success(result.data.message);
          } else {
            this.$Message.error(result.data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 预览问卷请求
    _previewExamAjax(formData, url) {
      const keyOne = "filter";
      generateAjax({ formData, url, keyOne })
        .then(result => {
          console.log("预览");
          console.log(result);
          if (result.data.code === "200") {
            let item = result.data.results;
            this.previewExams = item.list;
            this.$Message.success(result.data.message);
          } else {
            this.$Message.error(result.data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 预览问卷
    previewExam() {
      this._previewExamAjax(this.datas, PREVIEW_URL);
    },
    // 显示或隐藏题干
    showOrhide() {
      this.isHideStem = !this.isHideStem;
    },
    /**
     * 下载导入题干模板
     */
    downloadTemplate() {
      window.open(
        HOST +
          "/townScore/downTownScoreMoudle?fileName=secondExamMould.xlsx&chinaName=二类问卷上传模板.xlsx"
      );
    }
  },
  created() {
    // this.examId.examId = this.$route.params.id;
    this.datas.examId = this.$route.params.id;
    // // 初始化查询题干
    this._examQueryAjAX(this.datas, EXAMQUESTION_URL);
    // // 初始化请求预览问卷
    this._previewExamAjax(this.datas, PREVIEW_URL);
  }
};
</script>
<style scoped>
.departments {
  margin: 10px 0;
}
.departments div button {
  margin-left: 10px;
}

.questionnaire .question-title {
  margin: 10px;
}

.questionnaire .question-title h3 {
  text-align: left;
  margin-left: 100px;
}
.questionnaire .radio-items {
  margin: 10px 50px;
  font-size: 17px;
}
.questionnaire-container {
  width: 1200px;
}
.redFont {
  color: #ed4014;
  font-size: 18px;
}
</style>
<style>
.test-table .ivu-table-row-highlight td {
  background: rgba(45, 183, 245, 0.5);
}
</style>
